package com.isyscore.os.metadata.model.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.isyscore.os.metadata.utils.AesUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.crypto.encrypt.AesBytesEncryptor;

import java.time.LocalDateTime;

/**
 * @author fjZheng
 * @version 1.0
 * @date 2020/10/21 14:49
 */
@Data
@Log4j2
public class DataSource {
    @TableId(type= IdType.ASSIGN_ID)
    @JsonSerialize(using = ToStringSerializer.class)
    @ApiModelProperty("数据源主键ID")
    private Long id;

    @ApiModelProperty(hidden = true)
    private String userId;

    @TableField(condition = SqlCondition.LIKE)
    @ApiModelProperty(name = "数据源名称")
    private String name;

    @ApiModelProperty(name = "数据源IP")
    private String ip;

    @ApiModelProperty(name = "数据源端口")
    private String port;

    private String databaseName;

    private String userName;

    private String password;

    @ApiModelProperty(name = "数据源类型", allowableValues = "0,1,2,3,4,5,6,7",
            notes = "0 mysql;1 oracle;2 clickhouse; 3 sqlserver; 4 dm; 5 td; 6 pg,7 mariadb")
    private Integer type;
//    @TableLogic
    @ApiModelProperty(hidden = true)
    @Deprecated
    private Integer IsDelete;

    @TableField(fill = FieldFill.INSERT)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty(name = "创建时间")
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @ApiModelProperty("更新时间")
    private LocalDateTime updateTime;

    @ApiModelProperty(hidden = true)
    @Deprecated
    private Integer isDataWarehouse;

    @ApiModelProperty("上锁信息：{databaseName: \"\",isLocked: 0}")
    private String databaseConfig;

    @ApiModelProperty("租户ID")
    @TableField(fill = FieldFill.INSERT)
    private String tenantId;

    @ApiModelProperty(value = "连接类型", allowableValues = "BASIC,TNS")
    private String connectType;

    @ApiModelProperty(value = "BASIC下的连接类型", allowableValues = "ServiceName,SID")
    private String basicType;

    @ApiModelProperty(value = "ServiceName,SID的值")
    private String basicValue;

    public String getPassword() {
        return password;
    }

    /**
     * 兼容密码加密和没加密的情况。尝试解密失败后直接使用原文作为密码。
     */
    public  String getPlaintextPassword(){
        try {
           return AesUtil.decrypt(password);
        } catch (Exception e) {
            log.info("密码尝试解码失败,使用原文作为密码");
            return password;
        }
    }

}
